/* CoreUtil */
/* 工具类，类似java静态工具类 */
var $ = jQuery = layui.jquery;
var CoreUtil = (function() {
	var coreUtil = {};
	/* ajax请求 */
	coreUtil.sendAjax = function(url, params, ft, method, headers, noAuthorityFt, contentType, async) {
		var loadIndex = top.layer.load(0, {
			shade : false
		});
		$.ajax({
			url : url,
			cache : false,
			async : async == undefined ? true : async,
			data : params,
			type : method == undefined ? "POST" : method,
			contentType : contentType == undefined ? 'application/json; charset=UTF-8' : contentType,
			dataType : "json",
			beforeSend : function(request) {
				if (headers == undefined) {
				} else if (headers) {
					request.setRequestHeader("authorization", CoreUtil.getData("access_token"));
					request.setRequestHeader("refresh_token", CoreUtil.getData("refresh_token"));
				} else {
					request.setRequestHeader("authorization", CoreUtil.getData("access_token"));
				}
			},
			success : function(res) {
				top.layer.close(loadIndex);
				if (typeof ft == "function") {
					if (res.code == 401001) { // 凭证过期重新登录
						layer.msg("凭证过期请重新登录", {
							time : 2000
						}, function() {
							top.window.location.href = "/index/login";
						});
					} else if (res.code == 401002) { // 根据后端提示刷新token
						/* 记录要重复刷新的参数 */
						var reUrl = url;
						var reParams = params;
						var reFt = ft;
						var reMethod = method;
						var reHeaders = headers;
						var reNoAuthorityFt = noAuthorityFt;
						var reContentType = contentType;
						var reAsync = async;
						/* 刷新token，然后存入缓存 */
						CoreUtil.sendAjax("/sys/user/token", null, function(res) {
							if (res.code == 0) {
								CoreUtil.setData("access_token", res.data);
								/* 刷新成功后继续重复请求 */
								CoreUtil.sendAjax(reUrl, reParams, reFt, reMethod, reHeaders, reNoAuthorityFt, reContentType, reAsync);
							} else {
								layer.msg("凭证过期请重新登录", {
									time : 2000
								}, function() {
									top.window.location.href = "/index/login"
								});
							}
						}, "GET", true)
					} else if (res.code == 0) {
						!!ft && ft(res);
					} else if (res.code == 401008) {// 无权限响应
						layer.msg(res.msg)
						!!noAuthorityFt && noAuthorityFt(res);
					} else {
						layer.msg(res.msg);
					}
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				top.layer.close(loadIndex);
				if (XMLHttpRequest.status == 404) {
					top.window.location.href = "/404";
				} else {
					layer.msg("服务器好像除了点问题！请稍后试试");
				}
			}
		});
	};
	/* 表单数据封装成 json String */
	coreUtil.formJson = function(frm) { // frm：form表单的id
		var o = {};
		var a = $("#" + frm).serializeArray();
		$.each(a, function() {
			if (o[this.name] !== undefined) {
				if (!o[this.name].push) {
					o[this.name] = [ o[this.name] ];
				}
				o[this.name].push(this.value || '');
			} else {
				o[this.name] = this.value || '';
			}
		});
		return JSON.stringify(o);
	};
	coreUtil.setData = function(key, value) {
		layui.data('LocalData', {
			key : key,
			value : value
		});
	};
	coreUtil.getData = function(key) {
		return layui.data('LocalData')[key];
	};
	coreUtil.formattime = function(val) {
		var date = new Date(val);
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		month = month > 9 ? month : ('0' + month);
		var day = date.getDate();
		day = day > 9 ? day : ('0' + day);
		var hh = date.getHours();
		hh = hh > 9 ? hh : ('0' + hh);
		var mm = date.getMinutes();
		mm = mm > 9 ? mm : ('0' + mm);
		var ss = date.getSeconds();
		ss = ss > 9 ? ss : ('0' + ss);
		return year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
	};
	coreUtil.formatDate = function(val) {
		var date = new Date(val);
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		month = month > 9 ? month : ('0' + month);
		var day = date.getDate();
		day = day > 9 ? day : ('0' + day);
		return year + '-' + month + '-' + day;
	};
	coreUtil.getFirstDayOfWeek = function(date) {
		return CoreUtil.formatDate(CoreUtil.firstDayOfWeek(date));
	};
	coreUtil.firstDayOfWeek = function(date) {
		if (!date) {
			date = new Date();
		}
		var weekday = date.getDay() || 7; // 获取星期几，getDay()返回值是 0（周日） 到 6（周六）
		// 之间的一个整数。0||7为7，即weekday的值为1-7
		date.setDate(date.getDate() - weekday + 1);// 往前算（weekday-1）天，年份、月份会自动变化
		return date;
	};
	// 判断字符是否为空的方法
	coreUtil.isEmpty = function(obj) {
		return typeof obj == "undefined" || obj == null || obj == "";
	};
	coreUtil.selectUser = function(callBack) {
		CoreUtil.openSelectWind('/index/userSelect', 'operation_user_select_table', callBack, "用户选择");
	};
	coreUtil.openSelectWind = function(url, ele, callBack, title, area) {
		!!url && !!ele && layui.layer.open({
			type : 2,
			icon : 3,
			title : [ title || "选择", 'font-size:18px;' ],
			content : url,
			area : area || [ '470px', '435px' ],
			btn : [ '确定', '取消' ],
			btnAlign : 'c',
			scrollbar : false,
			yes : function(index, layero) {
				var iframeWindow = window['layui-layer-iframe' + index]
				var checkedDatas = iframeWindow.layui.table.checkStatus(ele);
				if (!!checkedDatas && !!checkedDatas.data && checkedDatas.data.length > 0) {
					!!callBack && "function" == typeof callBack && callBack(checkedDatas.data[0]);
				} else {
					layui.layer.msg('未选中任何数据！');
				}
				layui.layer.close(index);
			}
		});
	};
	coreUtil.exchangeSwitch = function(ele, txt, data) {
		if (data == txt) {
			ele.attr('checked', 'checked').attr('type', 'hidden').val(1);
			ele.next().attr("class", "layui-unselect layui-form-switch layui-form-onswitch");
			$(ele.next().children()[0]).text(data);
		} else {
			ele.attr('type', 'hidden').removeAttr("checked").val(0);
			ele.next().attr("class", "layui-unselect layui-form-switch");
			$(ele.next().children()[0]).text(data);
		}
	};
	return coreUtil;
})(CoreUtil, window);
